package com.java.base.exercise.current;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author RenPu
 * @Date 2022/1/8 10:31
 * @Version 1.0
 * @Description:
 **/
public class RequestQueue {

    private static final Integer sizeValue=1000;

    private Queue<String> queue = new ArrayBlockingQueue<String>(sizeValue);
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public String get(){
        String result=null;
        lock.lock();
        try {
        while (queue.isEmpty()){
               condition.await();  //阻塞等待
            }
            result = queue.poll(); //删除列头元素，有值取值，无值返回null
            condition.signalAll(); // 唤醒往队列里放入的操作
            } catch (InterruptedException e) {
            condition.signalAll(); //
            }finally {
            lock.unlock();
        }
        return result;
    }


    public void put(String E){
        lock.lock();
        try{
        //当queue的长度不小于sizeValue进行死循环等待
        while (queue.size()>=sizeValue){
                condition.await();
        }
        queue.offer(E);   //放入元素
        condition.signalAll(); //唤醒取出元素的操作
        }catch (InterruptedException e){
            condition.signalAll();
        }finally {
            lock.unlock();
        }

    }



}
